function init() {

	// register the callback
	if (wave && wave.isInWaveContainer()) {
		wave.setStateCallback(stateUpdated);
	}



	// register the listener
	$('#tabs').bind('tabsselect', function(event, ui) {
		// first check if we're updating
		var selected = parseInt(wave.getState().get('selected'));
		if (selected != -1) {
		  // we're updating, automatic selected, set selected to -1 to
		  // avoid updates cascading updates.
		  wave.getState().submitDelta( {'selected' : -1 });
		} else {
		  // we're not updating, so a manual click is used.
		  // set the delta
		  wave.getState().submitDelta( {'selected' : ui.index });
		}
		gadgets.window.adjustHeight();
	});
}

function stateUpdated() {
	
	// process the images, only do this once
	var imageCount = parseInt(wave.getState().get('headerCount'));
	if (!started) {
		for (i = 0 ; i < imageCount ; i++) {
			var headerName = wave.getState().get('header'+i);
			var urls = wave.getState().get('images'+i).split('|');
			addTab(i , headerName,urls);
		}
		
		// setup the tabs and make them vertical
		$tabs = $("#tabs").tabs();
		$("#tabs").tabs().addClass('ui-tabs-vertical ui-helper-clearfix');
		$("#tabs li").removeClass('ui-corner-top').addClass('ui-corner-left');
		started = true;
		gadgets.window.adjustHeight();
	}

	if (wave.getState() == null || !wave.getState().get('selected')) {
		// noop
	} else {
		// get selected from wave and from tabs
		var updateSelected = parseInt(wave.getState().get('selected'));
		var tabSelected = $('#tabs').tabs('option', 'selected');
		// only change if we're not already at the correct tab
		if (tabSelected != updateSelected) {
			$('#tabs').tabs('select', updateSelected);
			gadgets.window.adjustHeight();
		}
	}
}

function addTab(count, header, images) {
	// first update the headers
	myUL = document.getElementById('headers');
	li = document.createElement('li');
	a = document.createElement('a');
	a.href = "#header" + count;
	span = document.createElement('span');
	span.innerHTML = header;
	a.appendChild(span);
	li.appendChild(a);
	myUL.appendChild(li);
	
	var divToAppend = '<div id="header' + count + '">';
	for (key in images) {
		if (images[key].length > 0) {
			divToAppend = divToAppend + '<img src="' + images[key] + '"></img>';
		}
	}
	divToAppend = divToAppend + "</div>";
	
	// create the html
	$("#tabs").append(divToAppend);
}

var started = false;
gadgets.util.registerOnLoadHandler(init);